package com.itheima.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//定义拦截器(只能拦截方法)
public class MyInterceptor implements HandlerInterceptor {
    //前置处理（原始方法运行前执行）
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //对访问路径进行判断
        //request.getRequestURI()   获取相对路径
        //request.getRequestURL()   获取绝对路径
        Object username = request.getSession().getAttribute("username");
        if (username!=null){
            System.out.println("前置放行");
            return true;
        }
        //返回值为false则被拦截的处理器不再向下放行
        System.out.println("前置拦截");
        return false;
    }

    //后置处理（原始方法运行后执行，被拦截则不执行）
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    //完成时处理（拦截器最后执行的方法，无论原始方法是否执行）
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {

    }
}
